<template>
  <el-menu :default-active="activeMenu" mode="horizontal" @select="handleSelect">
    <template v-for="(item, index) in topMenus" :key="index">
      <el-menu-item :style="{ '--theme': theme }" :index="item.path" v-if="index < visibleNumber">
        <svg-icon
          v-if="item.meta && item.meta.icon && item.meta.icon !== '#'"
          :icon-class="item.meta.icon"
        />
        {{ item.meta?.title }}
      </el-menu-item>
    </template>

    <!-- 顶部菜单超出数量折叠 -->
    <el-sub-menu index="more" :key="visibleNumber" v-if="topMenus.length > visibleNumber">
      <template #title>更多菜单</template>
      <template v-for="(item, index) in topMenus" :key="index">
        <el-menu-item :index="item.path" v-if="index >= visibleNumber">
          <svg-icon
            v-if="item.meta && item.meta.icon && item.meta.icon !== '#'"
            :icon-class="item.meta.icon"
          />
          {{ item.meta?.title }}
        </el-menu-item>
      </template>
    </el-sub-menu>
  </el-menu>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { constantRoutes } from '@/router'
import { isHttp } from '@/utils/validate'
import type { RouteRecordRaw } from 'vue-router'
import type { MenuItemClicked } from 'element-plus/es/components/menu/src/types'

// 定义类型
interface Meta {
  title?: string
  icon?: string
  link?: string
}

interface CustomRouteRecord {
  hidden?: boolean
  meta?: Meta
  children?: CustomRouteRecord[]
  parentPath?: string
  query?: string
  path?: string
  redirect?: RouteRecordRaw['redirect']
  name?: RouteRecordRaw['name']
  component?: RouteRecordRaw['component']
  components?: RouteRecordRaw['components']
  props?: RouteRecordRaw['props']
  beforeEnter?: RouteRecordRaw['beforeEnter']
  childrenRoutes?: RouteRecordRaw['children']
}

// 隐藏侧边栏路由
const hideList = ['/index', '/user/profile']

const store = useStore()
const router = useRouter()
const route = useRoute()

// 顶部栏初始数
const visibleNumber = ref(5)
// 当前激活菜单的 index
const currentIndex = ref<string | undefined>(undefined)

const theme = computed(() => {
  return store.state.settings.theme
})

// 所有的路由信息
const routers = computed(() => {
  return store.state.permission.topbarRouters as CustomRouteRecord[]
})

const childRoutes = computed(() => {
  const currentRouteRecord = router.getRoutes().find((r) => r.name === route.name)
  return currentRouteRecord?.children || []
})

// 顶部显示菜单
const topMenus = computed(() => {
  const topMenus: CustomRouteRecord[] = []
  routers.value.map((menu) => {
    if (menu.hidden !== true) {
      // 兼容顶部栏一级菜单内部跳转
      if (menu.path === '/') {
        topMenus.push(menu.children?.[0] as CustomRouteRecord)
      } else {
        topMenus.push(menu)
      }
    }
  })
  return topMenus
})

// 设置子路由
const childrenMenus = computed(() => {
  const childrenMenus: (CustomRouteRecord | RouteRecordRaw)[] = []
  routers.value.map((routerItem) => {
    if (routerItem.children) {
      for (const item of routerItem.children) {
        const childItem = item as CustomRouteRecord
        if (childItem.parentPath === undefined) {
          if (routerItem.path === '/') {
            childItem.path = '/' + (childItem.path || '')
          } else {
            if (childItem.path && !isHttp(childItem.path)) {
              childItem.path = routerItem.path + '/' + childItem.path
            }
          }
          childItem.parentPath = routerItem.path
        }
        childrenMenus.push(childItem)
      }
    }
  })
  return [...constantRoutes, ...childrenMenus]
})

// 当前激活的路由
const activeRoutes = (key: string) => {
  const routes: (CustomRouteRecord | RouteRecordRaw)[] = []
  if (childrenMenus.value && childrenMenus.value.length > 0) {
    childrenMenus.value.map((item) => {
      // 类型安全检查
      const customItem = item as CustomRouteRecord
      if (key == customItem.parentPath || (key == 'index' && '' == (customItem.path || ''))) {
        routes.push(item)
      }
    })
  }
  if (routes.length > 0) {
    store.commit('SET_SIDEBAR_ROUTERS', routes)
  } else {
    store.dispatch('app/toggleSideBarHide', true)
  }
}

// 默认激活的菜单
const activeMenu = computed(() => {
  const path = route.path
  let activePath = path
  if (path !== undefined && path.lastIndexOf('/') > 0 && hideList.indexOf(path) === -1) {
    const tmpPath = path.substring(1, path.length)
    if (route.meta && !(route.meta as any).link) {
      activePath = '/' + tmpPath.substring(0, tmpPath.indexOf('/'))
      store.dispatch('app/toggleSideBarHide', false)
    }
  } else if (!childRoutes.value) {
    activePath = path
    store.dispatch('app/toggleSideBarHide', true)
  }
  activeRoutes(activePath)
  return activePath
})

// 根据宽度计算设置显示栏数
const setVisibleNumber = () => {
  const width = document.body.getBoundingClientRect().width / 3
  visibleNumber.value = parseInt(String(width / 85))
}

// 菜单选择事件
const handleSelect = (
  index: string,
  indexPath: string[],
  item: MenuItemClicked,
  routerResult?: Promise<void | import('vue-router').NavigationFailure>,
) => {
  currentIndex.value = index
  const routeItem = routers.value.find((item) => item.path === index)
  if (isHttp(index)) {
    // http(s):// 路径新窗口打开
    window.open(index, '_blank')
  } else if (!routeItem || !routeItem.children) {
    // 没有子路由路径内部打开
    const routeMenu = childrenMenus.value.find(
      (item) => (item as CustomRouteRecord).path === index,
    ) as CustomRouteRecord | undefined
    if (routeMenu && routeMenu.query) {
      try {
        const query = JSON.parse(routeMenu.query)
        router.push({ path: index, query: query })
      } catch (e) {
        router.push({ path: index })
      }
    } else {
      router.push({ path: index })
    }
    store.dispatch('app/toggleSideBarHide', true)
  } else {
    // 显示左侧联动菜单
    activeRoutes(index)
    store.dispatch('app/toggleSideBarHide', false)
  }
}

onMounted(() => {
  setVisibleNumber()
  window.addEventListener('resize', setVisibleNumber)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', setVisibleNumber)
})
</script>

<style lang="scss">
.topmenu-container.el-menu--horizontal > .el-menu-item {
  float: left;
  height: 50px !important;
  line-height: 50px !important;
  color: #999093 !important;
  padding: 0 5px !important;
  margin: 0 10px !important;
}

.topmenu-container.el-menu--horizontal > .el-menu-item.is-active,
.el-menu--horizontal > .el-submenu.is-active .el-submenu__title {
  border-bottom: 2px solid #{'var(--theme)'} !important;
  color: #303133;
}

/* submenu item */
.topmenu-container.el-menu--horizontal > .el-submenu .el-submenu__title {
  float: left;
  height: 50px !important;
  line-height: 50px !important;
  color: #999093 !important;
  padding: 0 5px !important;
  margin: 0 10px !important;
}
</style>
